import { useState, useEffect } from 'react';
import { Link, history, useRequest } from 'umi';
import {
  Table,
  Space,
  Card,
  Button,
  Form,
  Input,
  Breadcrumb,
  Modal,
  Empty,
  Row,
  Col,
  Select,
  message,
  Spin,
} from 'antd';
import {
  CloseOutlined,
  PlusOutlined,
  FolderOpenOutlined,
  RollbackOutlined,
} from '@ant-design/icons';
import { useLocalStorageState } from 'ahooks';
import { PageContainer } from '@ant-design/pro-layout';

import zhCN from 'antd/lib/locale/zh_CN';
const { Option } = Select;

const CreateIntelligentReport = () => {
  const [isModalVisible, setIsModalVisible] = useState(false); //保存modal
  const [smallVisible, setSmallVisible] = useState(false); //表名字subtitle modal
  const [preserveVisible, setPreserveVisible] = useState(false); //保存modal
  const [purposeVisible, setPurposeVisible] = useState(false); //用途modal

  const [cardsArray, setCardsArray] = useLocalStorageState('cardsArray', {
    defaultValue: [],
  }); //维护的Card数组，用来预览模板
  const [form] = Form.useForm();
  const [formSave] = Form.useForm(); //保存表单实例
  const [formBoard] = Form.useForm();
  const [formPurpose] = Form.useForm(); //用途表单实例

  //获取全部模板
  const getAllBoard = useRequest(
    (data = {}) => {
      return {
        url: 'http://10.1.40.84:9993/getAllBoard',
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        // console.log(JSON.parse(result));
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // manual: false,
    },
  );
  //根据boardId获取单个画板数据
  const getOneBoardData = useRequest(
    (boardId) => {
      return {
        url: `http://10.1.40.84:9993/getOneBoardData?boardId=${boardId}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      onSuccess: (result, params) => {
        // console.log(JSON.parse(result));
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
    },
  );
  //新建模板
  const addModule = useRequest(
    (data) => {
      return {
        url: `http://10.1.40.84:9993/addModule`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        // console.log(JSON.parse(result));
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
    },
  );
  //获取单个模板的数据
  const getOneModuleData = useRequest(
    (moduleId) => {
      return {
        url: `http://10.1.40.84:9993/getOneModuleData?moduleId=${moduleId}`,
        method: 'GET',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
      };
    },
    {
      onSuccess: (result, params) => {
        // console.log(JSON.parse(result));
        let cardsArrayTemp: any = [];
        result.data.map((item: any) => {
          cardsArrayTemp.push({
            cardId: item.boardId,
            cardTitle: item.blockName,
            cardDataSource: item.boardData,
            cardColumn: item.column,
          });
        });
        setCardsArray(cardsArrayTemp);
        formSave.setFieldsValue(result);
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
    },
  );
  //打印word的请求
  const createWord = useRequest(
    (data) => {
      return {
        url: `http://10.1.40.84:9993/createWord`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        window.open(result);
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
    },
  );
  //添加模版用途
  const addPurpose = useRequest(
    (data) => {
      return {
        url: `http://10.1.40.84:9993/addPurpose`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);

        // window.open(result);
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
    },
  );
  //获取所有用途
  const getAllPurpose = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9993/getAllPurpose`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
        // window.open(result);
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      // manual: true,
    },
  );
  //打印EXCEL
  const exportModuleExcel = useRequest(
    (data = {}) => {
      return {
        url: `http://10.1.40.84:9993/exportModuleExcel`,
        method: 'POST',
        headers: {
          Authorization: localStorage.getItem('token') || '',
        },
        data,
      };
    },
    {
      onSuccess: (result, params) => {
        console.log(result);
        window.open(result);
      },
      onError: (e, params) => {
        console.log(e);
        console.log(params);
      },
      manual: true,
    },
  );
  //判断是否需要请求数据
  useEffect(() => {
    const boardIdTemp = history.location.pathname.replace(
      '/IntelligentReport/CreateIntelligentReport/',
      '',
    );
    if (boardIdTemp !== 'new') {
      getOneModuleData.run(boardIdTemp);
    }
    return () => {
      setCardsArray([]);
    };
  }, []);
  //看板 原图加入
  const showSmallModal = (record: any) => {
    getOneBoardData.run(record.id).then(() => {
      form.resetFields();
      setSmallVisible(true);
    });
  };
  //看板 给原图起个名字 存入cardarray
  const handleSmallOk = () => {
    form
      .validateFields()
      .then((formdata: any) => {
        const { boardColumnMap, data, id } = getOneBoardData.data;
        let cardsArrayTemp: any = JSON.parse(JSON.stringify(cardsArray));
        cardsArrayTemp.push({
          cardId: id,
          cardTitle: formdata.Name,
          cardDataSource: data,
          cardColumn: boardColumnMap,
        });
        setCardsArray(cardsArrayTemp);
        setIsModalVisible(false);
        setSmallVisible(false);
      })
      .catch((info) => {
        console.log(info);
      });
  };
  //保存模板
  const handlePreserveOk = () => {
    formSave.validateFields().then((formdata: any) => {
      let boardList: any = [];
      cardsArray?.map((item: any) => {
        boardList.push({
          blockName: item.cardTitle,
          boardId: item.cardId,
        });
      });
      addModule
        .run({
          moduleName: formdata.moduleName,
          desc: formdata.desc,
          boardList: boardList,
          purposeId: formdata.purposeId,
        })
        .then(() => {
          setPreserveVisible(false);
          setCardsArray([]);
          history.push('/DataExport/IntelligentReport');
        });
    });
  };
  //删除卡片
  const deleteCard = (cardInfo: any) => {
    let cardsArrayTemp: any = JSON.parse(JSON.stringify(cardsArray));
    let finishCards: any = cardsArrayTemp.filter((card: any) => {
      return card.cardTitle !== cardInfo.cardTitle;
    });
    setCardsArray(finishCards);
  };
  //搜索
  const onFinish = (value: any) => {
    getAllBoard.run(value);
  };
  //模版用途ok
  const handlePurposeOk = () => {
    formPurpose
      .validateFields()
      .then((formdata: any) => {
        console.log(formdata);
        addPurpose.run(formdata).then((e) => {
          getAllPurpose.run();
          setPurposeVisible(false);
        });
      })
      .catch((info) => {
        console.log(info);
      });
  };
  const boardColumns = [
    {
      title: '看板名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: '主题',
      dataIndex: 'theme',
      key: 'theme',
      align: 'center',
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (_: any, record: any) => {
        return <a onClick={() => showSmallModal(record)}>原图加入</a>;
      },
    },
  ];
  return (
    <PageContainer
      header={{
        title: '新建智能报表',
        breadcrumb: (
          <Breadcrumb>
            <Breadcrumb.Item>数据导出</Breadcrumb.Item>
            <Breadcrumb.Item>智能报表</Breadcrumb.Item>
            <Breadcrumb.Item>新建智能报表</Breadcrumb.Item>
          </Breadcrumb>
        ),
      }}
    >
      {/* <Button onClick={() => {
        console.log(JSON.parse(getOneModuleData.data));
      }}>ceshi</Button> */}
      <div style={{ background: ' #ececec', width: '100%' }}>
        <Card
          title={
            getOneModuleData?.data
              ? getOneModuleData?.data?.name
              : ' 创建智能报表'
          }
          extra={
            <Space>
              {getOneModuleData?.data ? (
                <>
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={() => {
                      const { id } = getOneModuleData.data;
                      // console.log(JSON.parse(getOneModuleData.data));
                      exportModuleExcel.run({ moduleId: id });
                    }}
                  >
                    打印Excel
                  </Button>
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={() => {
                      const { name, data } = getOneModuleData.data;
                      let worldParam: any = {
                        title: name,
                        data: [],
                      };
                      data.map((card: any) => {
                        worldParam.data.push({
                          subTitle: card.blockName,
                          dataSource: card.boardData,
                          columns: card.column,
                        });
                      });
                      createWord.run(worldParam);
                    }}
                  >
                    打印word
                  </Button>
                </>
              ) : (
                <></>
              )}

              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => setIsModalVisible(true)}
              >
                添加
              </Button>
              <Button
                type="primary"
                icon={<FolderOpenOutlined />}
                onClick={() => {
                  setPreserveVisible(true);
                }}
              >
                保存
              </Button>
              <Link to={{ pathname: '/DataExport/IntelligentReport' }}>
                <Button
                  icon={<RollbackOutlined />}
                  onClick={() => {
                    setCardsArray([]);
                  }}
                >
                  返回
                </Button>
              </Link>
            </Space>
          }
        >
          {cardsArray?.length ? (
            cardsArray.map((card: any, index: any) => (
              <Card
                key={index}
                title={card.cardTitle}
                type="inner"
                size="small"
                style={index !== 0 ? { marginTop: 20 } : { marginTop: 0 }}
                extra={
                  <CloseOutlined
                    onClick={() => {
                      deleteCard(card);
                    }}
                  />
                }
              >
                <Table
                  rowKey={() => Math.random()}
                  columns={card.cardColumn}
                  dataSource={card.cardDataSource}
                  pagination={{
                    size: 'small',
                    hideOnSinglePage: true,
                    defaultPageSize: 5,
                  }}
                />
              </Card>
            ))
          ) : (
            <Row style={{ height: 400 }} align="middle" justify="center">
              <Col span={24}>
                <Spin spinning={getOneModuleData.loading}>
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                </Spin>
              </Col>
            </Row>
          )}
        </Card>

        <Modal
          title="添加看板"
          visible={isModalVisible}
          onOk={() => setIsModalVisible(false)}
          onCancel={() => setIsModalVisible(false)}
          width={1000}
          okText={'确定'}
          cancelText={'取消'}
          forceRender
        >
          <Card
            title={
              <Form
                onFinish={onFinish}
                layout="inline"
                size="small"
                form={formBoard}
              >
                <Form.Item label="看板名称" name="name">
                  <Input allowClear />
                </Form.Item>
                <Form.Item label="主题" name="theme">
                  <Select style={{ width: 120 }} allowClear>
                    <Option value="论文">论文</Option>
                    <Option value="专利">专利</Option>
                    <Option value="项目">项目</Option>
                    <Option value="成果">成果</Option>
                    <Option value="著作">著作</Option>
                    <Option value="实验平台">实验平台</Option>
                    <Option value="合作交流">合作交流</Option>
                    <Option value="社会服务">社会服务</Option>
                    <Option value="人才培养">人才培养</Option>
                  </Select>
                </Form.Item>
                <Form.Item label="创建人" name="account">
                  <Input allowClear />
                </Form.Item>
                <Form.Item>
                  <Button htmlType="submit" type="primary">
                    查询
                  </Button>
                </Form.Item>
                <Form.Item>
                  <Button
                    onClick={() => {
                      formBoard.resetFields();
                      getAllBoard.run();
                    }}
                  >
                    还原
                  </Button>
                </Form.Item>
              </Form>
            }
            bordered={false}
          >
            <Table
              rowKey={'id'}
              size="small"
              bordered
              columns={boardColumns}
              dataSource={getAllBoard.data || []}
              pagination={{ size: 'small', hideOnSinglePage: true }}
            />
          </Card>
        </Modal>
        <Modal
          title="报表项"
          visible={smallVisible}
          onOk={handleSmallOk}
          onCancel={() => setSmallVisible(false)}
          okText={'确定'}
          cancelText={'取消'}
          forceRender
        >
          <Form layout="horizontal" form={form}>
            <Form.Item
              label="报表项名称"
              name="Name"
              rules={[{ required: true }]}
            >
              <Input allowClear />
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          title="保存模版"
          visible={preserveVisible}
          onOk={handlePreserveOk}
          onCancel={() => setPreserveVisible(false)}
          okText={'保存'}
          cancelText={'取消'}
          forceRender
        >
          <Form
            layout="horizontal"
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 14 }}
            form={formSave}
            // defaultValue={getOneModuleData.data}
          >
            <Form.Item
              label="报表模版名称"
              name="moduleName"
              rules={[{ required: true }]}
            >
              <Input allowClear />
            </Form.Item>
            <Form.Item
              label="报表模版描述"
              name="desc"
              rules={[{ required: true }]}
            >
              <Input allowClear />
            </Form.Item>
            <Row>
              <Col span={16}>
                <Form.Item
                  label="报表模版用途"
                  name="purposeId"
                  rules={[{ required: true }]}
                  labelCol={{ span: 9 }}
                  wrapperCol={{ span: 15 }}
                >
                  <Select>
                    {getAllPurpose?.data?.map((item: any) => (
                      <Option value={item.id} key={item.id}>
                        {item.purposeName}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Button
                  type="link"
                  onClick={() => {
                    setPurposeVisible(true);
                  }}
                >
                  新增用途
                </Button>
              </Col>
            </Row>
          </Form>
        </Modal>

        <Modal
          title="新增模版用途"
          visible={purposeVisible}
          onOk={handlePurposeOk}
          onCancel={() => setPurposeVisible(false)}
          okText={'确定'}
          cancelText={'取消'}
          forceRender
        >
          <Form layout="horizontal" form={formPurpose}>
            <Form.Item
              label="模版用途名称"
              name="purposeName"
              rules={[{ required: true }]}
            >
              <Input allowClear />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </PageContainer>
  );
};

export default CreateIntelligentReport;
